<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="appStore.device === 'mobile'" class="default-theme">
        <!--用户数据-->
        <pane size="84">
          <el-col>


            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:employee:add']">新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['system:employee:edit']">修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:itemMer:remove']">删除</el-button>
              </el-col>
            </el-row>

            <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="50" align="center" />
              <el-table-column label="序号" align="center" prop="id" width="50" />
              <el-table-column label="交易项" align="center" key="itemName" prop="itemName"  />
              <el-table-column label="关联商户号" align="center" key="merchantId" prop="merchantId"  />
              <el-table-column label="比例(%)" align="center" key="proportion" prop="proportion"  />
              <el-table-column label="创建时间"  align="center" key="createTime" prop="createTime"  />
              <el-table-column label="修改时间" align="center" key="updateTime" prop="updateTime"  />
              <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
                <template #default="scope">
                  <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:employee:edit']">修改</el-button>
                  <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:itemMer:remove']">删除</el-button>
                  <el-button link type="primary"  @click="handleInfo(scope.row)" v-hasPermi="['system:employee:info']">详情</el-button>

                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form :model="form" :rules="rules" ref="userRef" label-width="110px">
        <el-row>

          <el-col :span="12">
            <el-form-item label="交易项" prop="itemName">
              <el-input v-model="form.itemName" placeholder="请输入交易项" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="比例(%)" prop="proportion">

              <el-input v-model="form.proportion" type="number" max="1" @input="handleInput" placeholder="请输入比例(%)" maxlength="3" >
                <template slot="append">%</template>
              </el-input>
              <span style="color: #333;font-size: 12px">分成比例=订单金额*n%</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收款账户" prop="merchantId">
              <el-select v-model="form.merchantId"  placeholder="请选择商户号">
                <el-option v-for="item in postOptions" :key="item.value" :label="item.name" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="itemTypeStr">
              <el-select v-model="form.itemTypeStr"  placeholder="请选择类型">
                <el-option label="卖方" value="1"></el-option>
                <el-option label="买方" value="2"></el-option>
<!--                <el-option v-for="item in postOptions" :key="item.value" :label="item.name" :value="item.value"></el-option>-->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否需要退款" prop="isRefund">
              <el-radio-group v-model="form.isRefund">
                <el-radio value="2">需要</el-radio>
                <el-radio value="1">不需要</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情 -->

    <el-dialog title="详情" v-model="infoopen" width="600px" append-to-body>
<!--      <div style="margin: 10px;font-size: 16px;font-weight: bold;">角色信息</div>-->
        <el-descriptions title="" direction="vertical" :column="3" border>
          <el-descriptions-item label="交易项">{{form.itemName}}</el-descriptions-item>
          <el-descriptions-item label="比例(%)">{{form.proportion}}%</el-descriptions-item>
          <el-descriptions-item label="关联商户号">{{form.merchantId}}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{form.createTime}}</el-descriptions-item>
          <el-descriptions-item label="修改时间">{{form.updateTime}}</el-descriptions-item>
        </el-descriptions>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="User">
import { getToken } from "@/utils/auth"
import useAppStore from '@/store/modules/app'
import {
  listUser,

  resetUserPwd,
  selectRoleAll,
  getStorechange,
  delUser,
  getUser,
  updateUser,
  addUser,
  deptTreeSelect,
  listStore
} from "@/api/configure/trade.js"
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"
// import {selectRoleAll} from "../../../api/company/store.js";

const router = useRouter()
const appStore = useAppStore()
const { proxy } = getCurrentInstance()
const { sys_normal_disable, sys_user_sex,sys_company_disable} = proxy.useDict("sys_normal_disable", "sys_user_sex","sys_company_disable")
const userList = ref([])
const tableData = ref([])
const open = ref(false)
const bgopen = ref(false)
const infoopen = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const names = ref([])
const listStores = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const dateRange = ref([])
const deptName = ref("")
const deptOptions = ref(undefined)
const enabledDeptOptions = ref(undefined)
const postOptions = ref([])
const roleOptions = ref([])
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,

  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/store/importData"
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    storeName: undefined,
  },
  rules: {
    merchantId: [
      { required: true, message: '请选择商户号', trigger: 'change' }
    ],
    itemName: [
      { required: true, message: '交易项不能为空', trigger: 'blur' }
    ],
    proportion: [
      { required: true, message: '比例(%)不能为空', trigger: 'blur' }
    ],
    itemTypeStr:[
      { required: true, message: '请选择类型', trigger: 'change' }
    ],
    isRefund:[
      { required: true, message: '请选择是否退款', trigger: 'change' }
    ]

  }
})

const { queryParams, form, rules } = toRefs(data)

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true
  return data.label.indexOf(value) !== -1
}

function handleInput(e){
  console.log('chufa')
  console.log(e)
    // 限制只能输入整数，并确保在 1-100 范围内
    let num = parseInt(e, 10);
    if (isNaN(num)) {
      form.value.proportion = '';
    } else {
      if (num < 1) num = 1;
      if (num > 100) num = 100;
      form.value.proportion = num;
    }
}

/** 根据名称筛选部门树 */
watch(deptName, val => {
  proxy.$refs["deptTreeRef"].filter(val)
})

/** 查询用户列表 */
function getList() {
  loading.value = true
  listUser(proxy.addDateRange(queryParams.value, dateRange.value)).then(res => {
    loading.value = false
    userList.value = res.rows
    total.value = res.total
  })
}


/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data
    enabledDeptOptions.value = filterDisabledDept(JSON.parse(JSON.stringify(response.data)))
  })
}

/** 过滤禁用的部门 */
function filterDisabledDept(deptList) {
  return deptList.filter(dept => {
    if (dept.disabled) {
      return false
    }
    if (dept.children && dept.children.length) {
      dept.children = filterDisabledDept(dept.children)
    }
    return true
  })
}

/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.value.deptId = data.id
  handleQuery()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  proxy.resetForm("queryRef")
  queryParams.value.deptId = undefined
  proxy.$refs.deptTreeRef.setCurrentKey(null)
  handleQuery()
}

/** 删除按钮操作 */
function handleDelete(row) {
  const userIds = row.id || ids.value
  console.log(userIds)
  proxy.$modal.confirm('是否确认删除序号"' + userIds + '"的数据项？').then(function () {
    return delUser(userIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("system/store/export", {
    ...queryParams.value,
  },`user_${new Date().getTime()}.xlsx`)
}



/** 更多操作 */
function handleCommand(command, row) {
  switch (command) {
    case "handleResetPwd":
      handleResetPwd(row)
      break
    case "handleAuthRole":
      handleAuthRole(row)
      break
    default:
      break
  }
}


/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)

  names.value = selection.map(item => item.name)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "用户导入"
  upload.open = true
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download("system/store/importTemplate", {
  }, `user_template_${new Date().getTime()}.xlsx`)
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true
}

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false
  upload.isUploading = false
  proxy.$refs["uploadRef"].handleRemove(file)
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
  getList()
}

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit()
}

/** 重置操作表单 */
function reset() {
  form.value = {
    managerId: undefined,
    name: undefined,
    address: undefined,
    managerPhone: undefined,
    mangerCard: undefined,
    mangerSex: undefined,
    roleId: undefined,
    remark: undefined,
    isIncumbency: undefined,
    incumTime: undefined,
    dimissionTime: undefined,
    isFranchise: undefined,
    accountNumber: undefined,
    accountAdd: undefined,

  }
  proxy.resetForm("userRef")
}

/*查看详情*/
function handleInfo(row){

  const userId = row.id || ids.value
  getUser(userId).then(response => {
    console.log(response)
    form.value = response.data
    infoopen.value = true
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  bgopen.value = false;
  infoopen.value = false;
  reset()
}

/** 新增按钮操作 */
function handleAdd() {
  reset()

  selectRoleAll().then(response => {

    postOptions.value = response.data
    console.log(response)
    open.value = true
    title.value = "添加交易项"
    console.log(response)
  })
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()

  selectRoleAll().then(response => {
    postOptions.value = response.data
  })
  const userId = row.id || ids.value
  getUser(userId).then(response => {
    form.value = response.data
    postOptions.value = response.posts
    roleOptions.value = response.roles
    form.value.postIds = response.postIds
    form.value.roleIds = response.roleIds
    open.value = true
    title.value = "修改交易项"
    form.password = ""
  })
  selectRoleAll().then(response => {
    postOptions.value = response.data
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["userRef"].validate(valid => {
    if (valid) {
      if (form.value.id != undefined) {
        updateUser(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addUser(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })

      }
    }
  })
}

onMounted(() => {
  getDeptTree()
  getList()
  /*proxy.getConfigKey("sys.user.initPassword").then(response => {
    initPassword.value = response.msg
  })*/
})
</script>
